﻿
namespace FileStrider {

    using System.IO;
    using System.Linq;

    public partial class FactsDs
    {
        public const int MaxFilesCount = 50;
        public const int MaxFoldersCount = 50;

        public const int ShowFoldersInReport = 10;

        public static FactsDataTable Folders;
        public static FactsDataTable Files;

        public static long SmallestFileSize;
        public static long SmallestFolderSize;

        public static void CheckFolderSize(string folder, long size)
        {
            if (size > SmallestFolderSize)
            {
                Folders.AddFactsRow(folder, size, folder);

                // check if there are more rows then MaxFolderCount
                // then remove a minimal size row
                if (MaxFoldersCount < Folders.Rows.Count)
                {
                    long s = GetSmallestFolderSize();
                    var smallestFolder = (from f in Folders
                                          where f.Size == s
                                          select f).First();
                    Folders.RemoveFactsRow(smallestFolder);
                    SmallestFolderSize = GetSmallestFolderSize();
                }
            }
        }

        public static FactsRow[] SortFolders()
        {
            var sortedFolders = from f in FactsDs.Folders orderby f.Size descending select f;
            return sortedFolders.ToArray();
        }

        public static FactsRow[] SortFiles()
        {
            var sortedFiles = from f in FactsDs.Files orderby f.Size descending select f;
            return sortedFiles.ToArray();
        }

        public static void CheckFileSize(FileInfo fileInfo)
        {
            if (fileInfo.Length > SmallestFileSize)
            {
                Files.AddFactsRow(fileInfo.FullName, fileInfo.Length, fileInfo.FullName);

                // check if there are more rows then MaxFileCount
                // then remove a minimal size row
                if (MaxFilesCount < Files.Rows.Count)
                {
                    long s = GetSmallestFileSize();
                    var smallestFile = (from f in Files
                                        where f.Size == s
                                        select f).First();
                    Files.RemoveFactsRow(smallestFile);
                    SmallestFileSize = GetSmallestFileSize();
                }
            }
        }

        private static long GetSmallestFolderSize()
        {
            var i = (from f in Folders
                     select f.Size).Min();

            return i;
        }

        private static long GetSmallestFileSize()
        {
            var i = (from f in Files
                     select f.Size).Min();

            return i;
        }
    }
}
